﻿using System;
using System.Collections.Generic;
using System.Text;

using Octopus.Logging;
using Octopus.Logging.Running;
using System.IO;

namespace Octopus.Logging.Impl.File
{
    public class RollingFileAppender : IAppender
    {
        private IVolatileConfigParser VParser = null;
        private FileWriter writer = null;
        private string path = string.Empty;

        private string GetFileName()
        {
            return path + "\\" + VParser.ReplaceVolatileConfig(this.File).Replace("%DateTime%", DateTime.Now.ToString(_DatePattern));
        }

        public void Init(LoggerRuningContext context, IVolatileConfigParser parser)
        {
            if (string.IsNullOrEmpty(File)) throw new Exception("Appender.File Not Set");
            if (parser == null) { throw new ArgumentNullException("IVolatileConfigParser For Appender Init Is Null"); }

            VParser = parser;
            VParser.SetVolatileRule("%BusinessLog.Name%", context.LogConfig.Name);
            VParser.SetVolatileRule("%ActionState%", context.LogInfo.ActionStateType);

            path = Path.GetFullPath(AppDomain.CurrentDomain.SetupInformation.ApplicationBase);
            writer = new FileWriter(GetFileName(), this.FlushTimeSpan);
        }

        public bool DoAppend(string content)
        {
            if (string.IsNullOrEmpty(content)) { return false; }

            //VParser.SetVolatileRule("%DateTime%", DateTime.Now.ToString(_DatePattern));
            writer.FileName = GetFileName();
            return writer.Write(content);
        }

        int _FlushTimeSpan;
        public int FlushTimeSpan
        {
            get { return _FlushTimeSpan; }
            set { _FlushTimeSpan = value; }
        }

        string _DatePattern;
        public string DatePattern
        {
            get { return _DatePattern; }
            set { _DatePattern = value; }
        }

        string _File;
        public string File
        {
            get { return _File; }
            set { _File = value; }
        }
    }
}
